package com.example.mq.mqserver;

import com.example.mq.common.*;
import com.example.mq.mqserver.core.BasicProperties;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
public class BrokerServer {
    private final ServerSocket serverSocket;
    // 目前只支持一个虚拟主机
    private final VirtualHost virtualHost = new VirtualHost("default");
    // 存储当前所有的会话，key：channelId，value：对应的 Socket 对象
    private final ConcurrentHashMap<String, Socket> sessions = new ConcurrentHashMap<>();
    // 这个线程池，用于处理多个客户端的请求
    private ExecutorService executorService = null;
    // 控制服务器是否继续运行
    private volatile boolean runnable = true;

    public BrokerServer (int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    /**
     * 启动 BrokerServer
     */
    public void start() throws IOException {
        log.info("BrokerServer 启动！");
        executorService = Executors.newCachedThreadPool();
        try {
            while (runnable) {
                Socket clientSocket = serverSocket.accept();
                executorService.submit(() -> {
                   processConnection(clientSocket);
                });
            }
        } catch (SocketException e) {
            log.info("服务器停止运行！");
        }
    }

    /**
     * 停止 BrokerServer
     */
    public void stop() throws IOException {
        // 一般都是通过 kill 进程来停止
        //  这里搞一个主要为了后续的单元测试
        runnable = false;
        // 停止线程池，丢弃目前正在执行的任务
        executorService.shutdownNow();
        serverSocket.close();
    }

    /**
     * 处理一个客户端连接
     */
    private void processConnection(Socket clientSocket) {
        // 在一个 Connection 中 可能涉及到多个请求和响应
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()) {
            try (DataInputStream dataInputStream = new DataInputStream(inputStream);
                 DataOutputStream dataOutputStream = new DataOutputStream(outputStream)) {
                while (true) {
                    // 1. 读取并解析请求
                    Request request =  readRequest(dataInputStream);
                    // 2. 根据请求计算响应
                    Response response = process(request, clientSocket);
                    // 3. 返回响应
                    writeResponse(dataOutputStream, response);
                }
            }
        } catch (EOFException | SocketException e) {
            // dataInputStream 读到末尾，会抛出 EOFException 异常
            // 或者客户端关闭连接，抛出 SocketException 异常
            // 这两个异常视为 正常情况，用来结束循环
//            e.printStackTrace();
            log.info("Connection 关闭！客户端地址：" + clientSocket.getInetAddress().toString()
                    + ":" + clientSocket.getPort());
        } catch (IOException | ClassNotFoundException | MQException e) {
            log.info("Connection 出现异常");
            e.printStackTrace();
        } finally {
            try {
                // 关闭连接
                clientSocket.close();
                // 一个 TCP 连接中，可能包含多个 channel
                // 清理当前连接对应的所有 channel
                clearClosedSession(clientSocket);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 按照自定义协议格式，读取请求
     */
    private Request readRequest(DataInputStream dataInputStream) throws IOException {
        Request request = new Request();
        // 1. 读取请求类型
        request.setType(dataInputStream.readInt());
        // 2. 读取 payload 长度
        request.setLength(dataInputStream.readInt());
        // 3. 读取 payload
        byte[] payload = new byte[request.getLength()];
        int n = dataInputStream.read(payload);
        if (n != request.getLength()) {
            throw new IOException("读取请求格式出错！");
        }
        request.setPayload(payload);
        return request;
    }

    /**
     * 按照自定义协议格式，返回响应
     */
    private void writeResponse(DataOutputStream dataOutputStream, Response response) throws IOException {
        dataOutputStream.writeInt(response.getType());
        dataOutputStream.writeInt(response.getLength());
        dataOutputStream.write(response.getPayload());
        // 刷新缓冲区
        dataOutputStream.flush();
    }

    /**
     * 根据请求计算响应
     */
    private Response process(Request request, Socket clientSocket) throws IOException, ClassNotFoundException, MQException {
        // 1. 初步解析 request 中的 payload
        BasicArguments basicArguments = (BasicArguments) BinaryTool.fromBytes(request.getPayload());
        log.info("[request] rid=" + basicArguments.getRid() + ", channelId=" + basicArguments.getChannelId()
                + ", type=" + request.getType() + ", length=" + request.getLength());
        // 2. 根据 type 进一步解析
        boolean ok = true;
        if (request.getType() == 0x1) {
            // 创建 channel
            sessions.put(basicArguments.getChannelId(), clientSocket);
            log.info("创建 channel 完成！channelId=" + basicArguments.getChannelId());
        } else if (request.getType() == 0x2) {
            // 销毁 channel
            sessions.remove(basicArguments.getChannelId());
            log.info("销毁 channel 完成！channelId=" + basicArguments.getChannelId());
        } else if (request.getType() == 0x3) {
            // 创建交换机，此时 payload 是一个 ExchangeDeclareArguments 对象了
            ExchangeDeclareArguments arguments = (ExchangeDeclareArguments) basicArguments;
            ok = virtualHost.exchangeDeclare(arguments.getExchangeName(), arguments.getExchangeType(),
                    arguments.isDurable(), arguments.isAutoDelete(), arguments.getArguments());
        } else if (request.getType() == 0x4) {
            // 销毁交换机
            ExchangeDeleteArguments arguments = (ExchangeDeleteArguments) basicArguments;
            ok = virtualHost.exchangeDelete(arguments.getExchangeName());
        } else if (request.getType() == 0x5) {
            // 创建队列
            QueueDeclareArguments arguments = (QueueDeclareArguments) basicArguments;
            ok = virtualHost.queueDeclare(arguments.getQueueName(), arguments.isDurable(),
                    arguments.isExclusive(), arguments.isAutoDelete(), arguments.getArguments());
        } else if (request.getType() == 0x6) {
            // 销毁队列
            QueueDeleteArguments queueDeleteArguments = (QueueDeleteArguments) basicArguments;
            ok = virtualHost.queueDelete(queueDeleteArguments.getQueueName());
        } else if (request.getType() == 0x7) {
            // 创建绑定
            QueueBindArguments arguments = (QueueBindArguments) basicArguments;
            ok = virtualHost.queueBind(arguments.getQueueName(), arguments.getExchangeName(), arguments.getBindingKey());
        } else if (request.getType() == 0x8) {
            // 销毁绑定
            QueueUnbindArguments arguments = (QueueUnbindArguments) basicArguments;
            ok = virtualHost.queueUnbind(arguments.getQueueName(), arguments.getExchangeName());
        } else if (request.getType() == 0x9) {
            // 发送消息
            BasicPublishArguments arguments = (BasicPublishArguments) basicArguments;
            ok = virtualHost.basicPublish(arguments.getExchangeName(), arguments.getRoutingKey(),
                    arguments.getBasicProperties(), arguments.getBody());
        } else if (request.getType() == 0xa) {
            // 订阅消息
            BasicConsumeArguments arguments = (BasicConsumeArguments) basicArguments;
            ok = virtualHost.basicConsume(arguments.getConsumerTag(), arguments.getQueueName(), arguments.isAutoAck(), new Consumer() {
                @Override
                public void handleDelivery(String consumerTag, BasicProperties basicProperties, byte[] body) throws MQException, IOException {
                    // 这个回调函数，就是将收到的消息，返回给对应的消费者
                    // 这个 consumerTag 就是 channelId
                    // 通过 channelId 在 sessions 哈希表中找到对应的 Socket 对象
                    // 然后就可以将消息返回给对应的客户端
                    // 1. 根据 channelId 获取 Socket 对象
                    Socket clientSocket = sessions.get(consumerTag);
                    if (clientSocket == null || clientSocket.isClosed()) {
                        System.out.println(clientSocket);
                        throw new MQException("[BrokerServer] 订阅消息的客户端已经关闭连接！");
                    }
                    // 2. 构造响应数据
                    // 此处要给消费者推送消息
                    // type 是 0xc
                    // payload 是 SubScribeReturns 对象进行序列化

                    // 1) 构造 payload
                    SubScribeReturns subScribeReturns = new SubScribeReturns();
                    subScribeReturns.setRid(""); // 服务器给消费者推送消息，只有响应，没有请求，所以这个 rid 没用
                    subScribeReturns.setChannelId(consumerTag);
                    subScribeReturns.setConsumerTag(consumerTag);
                    subScribeReturns.setBasicProperties(basicProperties);
                    subScribeReturns.setBody(body);
                    byte[] payload = BinaryTool.toBytes(subScribeReturns);
                    // 2) 构造响应
                    Response response = new Response();
                    response.setType(0xc);
                    response.setLength(payload.length);
                    response.setPayload(payload);

                    log.info("【推送消息】 channelId=" + consumerTag
                            + ", type=" + response.getType() + ", length=" + response.getLength());

                    // 3. 发送响应
                    DataOutputStream dataOutputStream = new DataOutputStream(clientSocket.getOutputStream());
                    synchronized (clientSocket) {
                        writeResponse(dataOutputStream, response);
                    }
                    // 此处不能关闭 dataOutputStream
                    // 因为，关闭 dataOutputStream，会导致 clientSocket 也被关闭
                    // clientSocket 被关闭了，后续就不能继续推送消息。
                }
            });
        } else if (request.getType() == 0xb) {
            // 确认消息
            BasicAckArguments arguments = (BasicAckArguments) basicArguments;
            ok = virtualHost.basicAck(arguments.getQueueName(), arguments.getMessageId());
        } else {
            throw new MQException("[BrokerServer] 未知的请求类型！type=" + request.getType());
        }
        // 3. 构造 payload
        BasicReturns basicReturns = new BasicReturns();
        basicReturns.setRid(basicArguments.getRid());
        basicReturns.setChannelId(basicArguments.getChannelId());
        basicReturns.setOk(ok);
        byte[] payload = BinaryTool.toBytes(basicReturns);
        // 4. 构造响应
        Response response = new Response();
        response.setType(request.getType());
        response.setLength(payload.length);
        response.setPayload(payload);
        log.info("[Response] rid=" + basicReturns.getRid() + ", channelId=" + basicReturns.getChannelId()
                + ", type=" + response.getType() + ", length=" + response.getLength());
        return response;
    }


    /**
     * 清理过期的会话
     * 一个连接可以有多个 channel
     * 通过 sessions 这个表来存储
     * 当一个连接关闭后
     * 需要清理 sessions 无效的会话
     */
    private void clearClosedSession(Socket clientSocket) {
        List<String> toDeleteChannelId = new ArrayList<>();
        for (Map.Entry<String, Socket> entry : sessions.entrySet()) {
            if (clientSocket == entry.getValue()) {
                // 不能一边遍历，一边删除
                // sessions.remove(entry.getKey());
                toDeleteChannelId.add(entry.getKey());
            }
        }
        for (String channelId : toDeleteChannelId) {
            sessions.remove(channelId);
        }
        log.info("清理 session 完成！channelId=" + toDeleteChannelId);
    }
}
